﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BusinessObjects;
using DataObjects.EntityFramework.ModelMapper;
using System.Linq.Dynamic;

namespace DataObjects.EntityFramework.Implementation
{
    public class EntityProvinceDao : IProvinceDao
    {
        public Province GetProvince(int ProvinceId)
        {
            using (var context = DataObjectFactory.CreateContext())
            {
                return Mapper.Map(context.ProvinceEntities.FirstOrDefault(p => p.ProvinceId == ProvinceId));
            }
        }
        public List<Province> GetProvinces(string sortExpression = "ProvinceName ASC")
        {
            using (var context = DataObjectFactory.CreateContext())
            {
                var list = new List<Province>();

                var provinces = context.ProvinceEntities.AsQueryable().OrderBy(sortExpression).ToList();
                foreach (var province in provinces)
                    list.Add(Mapper.Map(province));

                return list;
            }
        }
        public void InsertProvince(Province province)
        {
            var entity = Mapper.Map(province);

            using (var context = DataObjectFactory.CreateContext())
            {
                context.ProvinceEntities.AddObject(entity);
                context.SaveChanges();

                // update business object with new version and id
                province.ProvinceId = entity.ProvinceId;

                //country.Version = Convert.ToBase64String(entity.Version);
            }
        }
        public void UpdateProvince(Province province)
        {
            using (var context = DataObjectFactory.CreateContext())
            {
                var entity = context.ProvinceEntities.Where(p => p.ProvinceId == province.ProvinceId).SingleOrDefault();

                entity.ProvinceId = province.ProvinceId;
                entity.CountryId = province.CountryId;
                entity.ProvinceName = province.ProvinceName;

                context.ProvinceEntities.ApplyCurrentValues(entity);
                context.SaveChanges();

                // Update business object with new version
                //country.Version = Convert.ToBase64String(entity.Version);
            }
        }
        public void DeleteProvince(Province province)
        {
            using (var context = DataObjectFactory.CreateContext())
            {
                var entity = context.ProvinceEntities.Where(c => c.ProvinceId == province.ProvinceId).SingleOrDefault();
                context.ProvinceEntities.DeleteObject(entity);
                context.SaveChanges();
            }
        }
    }
}
